package com.example.administrator.diary;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.diary.Fields.DiaryColumns;


import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.List;

public class DiaryMain extends AppCompatActivity {

    private List<Integer> bn;
    private long Itemid;
    public static int theme=R.style.AppTheme;
    public ListView listView;
    private  String[] PROJECTION =
            new String[] { DiaryColumns._ID,
                    DiaryColumns.TITLE, DiaryColumns.CREATED };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState!=null)
        {
            theme=savedInstanceState.getInt("theme");
            setTheme(theme);
        }

        setContentView(R.layout.diarylist);
        listView=(ListView)findViewById(R.id.showit);
        Intent intent = getIntent();
        if (intent.getData() == null) {
            intent.setData(DiaryColumns.CONTENT_URI);
        }
        Cursor cursor = managedQuery(getIntent().getData(),
                PROJECTION, null,null, DiaryColumns.DEFAULT_SORT_ORDER);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor, new String[]
                { DiaryColumns.TITLE,DiaryColumns.CREATED },
                new int[] { R.id.text1,R.id.created });

//        MyAdapter madapter = new MyAdapter(this,
//                R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
//                DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created },R.id.checkBox,DiaryColumns._ID);
//        bn=madapter.getSelectedItems();
        listView.setAdapter(adapter);

        //listview点击响应事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
                Bundle data=new Bundle();
                data.putInt("theme",theme);
                Intent intent1=new Intent(DiaryEditor.EDIT_DIARY_ACTION, uri);
                intent1.putExtra("data",data);
                startActivity(intent1);
            }
        });

        //listview长按删除
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Itemid=id;
                AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(DiaryMain.this,
                        R.style.AlertDialogCustom));
                builder.setTitle("提示").setMessage("确定要删除？").setPositiveButton("确定",new
                 DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = ContentUris.withAppendedId(getIntent().getData(),
                                                Itemid);
                                getContentResolver().delete(uri, null, null);
                                renderListView();
                                setResult(RESULT_OK);
                    }

                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
                return true;

            }
        });

    }
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main,menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.action_add:
                Intent intent0 = new Intent(this, DiaryEditor.class);
                intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
                intent0.setData(getIntent().getData());
                startActivity(intent0);
                return true;
            case R.id.action_nmode:
                theme=(theme==R.style.AppTheme)?R.style.NightAppTheme:R.style.AppTheme;
                recreate();
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        //renderListView();
    }
    private void renderListView() {
        Cursor cursor = managedQuery(getIntent().getData(), PROJECTION,
                null,null, DiaryColumns.DEFAULT_SORT_ORDER);

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
                R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
                DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created });
//        MyAdapter madapter = new MyAdapter(this,
//                R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
//                DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created },R.id.checkBox,DiaryColumns._ID);
//        listView.setAdapter(adapter);
        listView.setAdapter(adapter);
    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("theme", theme);
    }


    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        theme = savedInstanceState.getInt("theme");
    }


//    class MyAdapter extends SimpleCursorAdapter {
//
//        private ArrayList<Integer> selection = new ArrayList<Integer>();//记录被选中条目id
//        private int mCheckBoxId = 0;//listView条目的样式对应的xml资源文件名（必须包含checkbox）
//        private String mIdColumn;//数据库表的id名称
//        public MyAdapter(Context context, int layout, Cursor c, String[] from, int[] to,int checkBoxId,String IdColumn) {
//            super(context, layout, c, from, to);
//            this.mCheckBoxId=checkBoxId;
//            this.mIdColumn=IdColumn;
//        }
//
//        @Override
//        public int getCount() {
//            return super.getCount();
//        }
//
//        @Override
//        public Object getItem(int position) {
//            return super.getItem(position);
//        }
//
//        @Override
//        public long getItemId(int position) {
//            return super.getItemId(position);
//        }
//
//        @Override
//        public View getView(final int position, View convertView,
//                            ViewGroup parent)
//        {
//            View view = super.getView(position, convertView, parent);
//            final CheckBox checkbox = (CheckBox) view.findViewById(mCheckBoxId);
//            checkbox.setOnClickListener(new View.OnClickListener()
//            {
//                @Override
//                public void onClick(View v)
//                {
//                    Cursor cursor = getCursor();
//                    cursor.moveToPosition(position);
//
//                    checkbox.setChecked(checkbox.isChecked());
//                    if(checkbox.isChecked())//如果被选中则将id保存到集合中
//                    {
//                        selection.add(cursor.getInt(cursor.getColumnIndex(mIdColumn)));
//                    }
//                    else//否则移除
//                    {
//                        selection.remove(new Integer(cursor.getInt(cursor.getColumnIndex(mIdColumn))));
//                    }
//                }
//            });
//
//            return view;
//        }
//        public ArrayList<Integer> getSelectedItems()
//        {
//            return selection;
//        }
//    }
}
